import { login, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import profileApi from '@/api/profile/profile'

const user = {
  state: {
    token: getToken(),
    avatar: '',
    roles: [],
    nickname:''
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, nickname) => {
      state.nickname = nickname
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {
    // 登录
    Login({ commit }, admin) {
      return new Promise((resolve, reject) => {
        login(admin).then(response => {
          const data = response.data
          setToken(data.token)
          commit('SET_TOKEN', data.token)
          commit('SET_NAME',data.admin.nickname)
          commit('SET_AVATAR',data.admin.avatar)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const data = response.data
          if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', data.roles)
          } else {
            reject('getInfo: roles must be a non-null array !')
          }
          commit('SET_NAME', data.admin.nickname)
          commit('SET_AVATAR', data.admin.avatar)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    }, 

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')//token
        commit('SET_ROLES', [])//角色
        commit('SET_NAME','')//真实姓名
        commit('SET_AVATAR','')//头像
        removeToken()
        resolve()
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

    //修改用户真实姓名
    Update({ commit }, admin) {
      return new Promise((resolve, reject) => {
        profileApi.updateNickname(admin).then(response => {
          const data = response.data
          setToken(data.token)
          commit('SET_TOKEN', data.token)
          commit('SET_NAME',admin.nickname)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    //修改用户的头像
    Avatar({commit},avatar){
      commit('SET_AVATAR',avatar)
    }
  }
}

export default user